/*******************************************************************
//  Encrypted OFDM System  (Transmitter)
//  DES -> Constellation mapping -> IFFT
//   
//  Date : 04/11/2011
//  Jungmin Park
********************************************************************/

#include "transmitter_receiver.h"

void transmitter (char *x, char *key, float *Y_re, float *Y_im)
{
	long a, b;
	float X_re[16];
	float X_im[16];
    int i;
	long temp;
    des_ctx dc;
	char *cp;

	printf (" ============  Transmitter ================= \n");
	printf ("-------- Input Strings [64 .... 0] of Transmitter----------\n"); 
	for (i=0; i<8; i++)
	{
		printf ("%02x", x[i] & 0x00FF);
	}
	printf ("\n");

    cp = x;
    des_key(&dc,key);
    des_enc(&dc,cp,1);      // DES Encryption 

	printf ("-------- Encrypted Strins [64 ... 0] --------- \n");
	for (i=0 ; i<8 ; i++)
	{
		printf ("%02x", x[i]& 0x00FF);
	}
	printf ("\n");

    a = (*cp&0x00ff) << 24 | (*(cp+1)&0x00ff) << 16 | (*(cp+2)&0x00ff) << 8 | (*(cp+3)&0x00ff) ;
    b = (*(cp+4)&0x00ff) << 24 | (*(cp+5)&0x00ff) << 16 | (*(cp+6)&0x00ff) << 8 | (*(cp+7)&0x00ff) ;
		
    temp = b;
	for (i=0; i<16; i++)             // Constellation mapping (16 QAM) 
	{
		 if (i == 8) temp=a;
		 constellation_mapping(temp, X_re+i, X_im+i);   
		 temp >>= 4;		 
	}
	
	FFT (0, X_re, X_im, Y_re, Y_im);  // Inverse FFT
	
	printf ("\n");
	
	printf ("-------- The output of Transmitter ----------\n"); 
	for (i=0; i<16; i++)
	{
		printf ("Y[%d] = %f+i%f \n", i, Y_re[i], Y_im[i]);
	}
    printf ("\n");
}

void receiver (char *x, char *key, float *X_re, float *X_im)
{	
    char a[16];
	char b[8];
    int i;
	des_ctx dc;
	char *cp;
	float Y_re [16];
	float Y_im [16];

    des_key(&dc,key);
	FFT (1, X_re, X_im, Y_re, Y_im); // FFT
	
	for (i=0; i < 16; i++)        // Inverse constellation mapping
	{
		inverse_constellation_mapping (a+(15-i), Y_re[i], Y_im[i]);
	}

	printf ("============ Receiver Part ============ \n");
	printf ("-------- The Input values  ----------\n"); 
	for (i=0; i<16; i++)
	{
		printf ("Y[%d] = %f+i%f \n", i, Y_re[i], Y_im[i]);
	}

	for (i=0; i< 8 ;i++)
	{
		b[i] = (a[2*i] & 0x0f) << 4 | (a[2*i+1] & 0x0f) ;
		printf ("%02x ", b[i] & 0x00ff);
 	}
	printf ("\n");

	cp = b;
	des_dec(&dc,cp,1);     // Decryption 

	printf ("-------- Output Strings of receiver [64 ... 0] ----------\n"); 
	for (i=0; i<8; i++)
	{
		printf ("%02x", b[i] & 0x00FF);
	}
	printf ("\n");
}	

